package Services


import(
	"github.com/gin-gonic/gin"
	"fmt"
	"net/http"
	"gin/Databases"
	"gin/Common"
	"encoding/json"
)

// 视图函数
func DisplayCodeData(c *gin.Context) {
	var s_type string
	var s_code string
	var s_name string
	//var s_relation string
	s_type = c.Query("type")
	s_code = c.Query("code")
	s_name = c.Query("name")
	//s_relation = c.Query("relation")
	fmt.Println("no data" + s_type + s_name)

	var i_type = Common.GetEntityType(s_type)
	//var i_relation,_ = strconv.Atoi(s_relation)
	var entitys []Common.Entity
	//sql := "select Fname,Fcode,Ftype,Fmatch_text from entity_match ORDER BY RAND() limit 1;"
	sql := "select Fname,Fcode,Fentity_type,Frealtion_id,Fmatch_text from entity_match where Fcode=? and Fentity_type=? order by Frealtion_id;"
	fmt.Println("sql:", sql)
	err := Databases.Db.Select(&entitys, sql, s_code, i_type)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
	        "result": -1,
	        "msg":    "query fail",
	        "data": "{}",
	    })
		fmt.Println("exec failed, ", err)
		return
	}

	if len(entitys) < 1 {
		c.JSON(http.StatusOK, gin.H{
	        "result": -1,
	        "msg":    "no data",
	        "data": "{}",
	    })
		fmt.Println("no data")
		return	
	}
	var attr_data_all Common.AttrDataAll
	attr_data_all.Name = entitys[0].Name
	attr_data_all.Code = entitys[0].Code

	for i := 0; i < len(entitys); i++ {
		var attr_data Common.AttrData
		attr_data.AttrId   = entitys[i].Relation
		attr_data.AttrData = entitys[i].Data
		attr_data_all.Attrdata = append(attr_data_all.Attrdata, attr_data)
	}
	/*
	if len(entitys) != 1 {
		c.JSON(http.StatusOK, gin.H{
	        "result": -1,
	        "msg":    "no data",
	        "data": "{}",
	    })
		fmt.Println("no data")
		return	
	}*/


	str, _ := json.Marshal(attr_data_all)
    str_res := string(str)
    c.JSON(http.StatusOK, gin.H{
        "result": 0,
        "msg":    "success",
        "data": str_res,
    })
}